from mongokit import Connection, ObjectId
from mongokit import ObjectId
from datetime import time, datetime, timedelta
db = Connection('127.0.0.1', 27017)

type='film'
start= datetime(2014,03,01,0,0,0)
end=datetime(2014,04,01,0,0,0)
limit=10
ascending=-1
topview =  db.fteluv.statistic.aggregate([{"$match":{"timestamp": {"$gte": start, "$lt": end}}},   \
                                    {"$group":{"_id":"$video_id", "total": {"$sum": 1}}},   \
                                    {"$sort":{"total":ascending}}])

topview2 =  db.fteluv.statisticbakup.aggregate([{"$match":{"timestamp": {"$gte": start, "$lt": end}}},   \
                                    {"$group":{"_id":"$video_id", "total": {"$sum": 1}}},   \
                                    {"$sort":{"total":ascending}}])

for index in topview2['result']:
    for i in range(0,len(topview['result'])):
        if index['_id'] == topview['result'][i]['_id']:
            topview['result'][i][u'total'] += index[u'total']


result = []
newlist = sorted(topview['result'], key=lambda k: k[u'total'], reverse=True)
i = 1
for index in newlist:
    if i>limit:
        break
    query = db.fteluv.videos_ver2.find_one({'_id':ObjectId(index['_id']), 'type': type})
    if query != None :
        i += 1
        item = {'video_name': query['title'], 'view_count': index[u'total'], 'video_id': str(query['_id'])}
        print item
        result.append(item)
print "DONE"